
int limit(int mn,int in,int mx) 
{
  int out;

  if (in<mn) out=mn;
  else if (in>mx) out=mx;
  else out=in;

  return out;
}

float flimit(float mn,float in,float mx)
{
  float out;
  
  if (in<mn) out=mn;
  else if (in>mx) out=mx;
  else out=in;

  return out;
}

void SGFilter(int &rawIn, int vect[])
{
  //Savitzky-Golay Filter
  for(int i = 0; i<numReadings-1; i++)
    vect[i] = vect[i+1];
  
  vect[6]=rawIn;
  
  rawIn = ((-2*vect[0]) + (3*vect[1]) + (6*vect[2]) + (7*vect[3]) + (6*vect[4]) + (3*vect[5]) - (2*vect[6]))/21;
} 

void SGFilterDB(double &rawIn, double vect[])
{
  //Savitzky-Golay Filter
  for(int i = 0; i<numReadings-1; i++)
    vect[i] = vect[i+1];
  
  vect[6]=rawIn;
  
  rawIn = ((-2*vect[0]) + (3*vect[1]) + (6*vect[2]) + (7*vect[3]) + (6*vect[4]) + (3*vect[5]) - (2*vect[6]))/21;
} 



/***************************************************************************************************************************/
void readString(char *line)
{
  byte index = 0;
  byte timeout = 0;
  byte ch=0;
  byte cont=1;
  
  do {
    if (Serial.available() == 0) {
      delay(20);
      timeout++;
      cont=1;
    }
    else {
      ch= Serial.read();
      line[index] =ch;
      timeout = 0;
      cont=0;
      if (ch=='>' || ch=='<') // immediate GUI command
      {
        index++;
        line[index++]=Serial.read();
      } 
      else if (ch!=';' && ch!=' ')
      {
        cont=1;
        index++;
      }
    }
  } while ( cont && timeout<5 && index<64);
  line[index]=0;
}

boolean cmpString(char *a,char *b)
{
  return strcmp(a,b)==0; // todo
}

void separator()
{
  Serial.print(";");
}

void ok()
{
  Serial.println("ok");
}


// Used to read floating point values from the serial port
float readFloatAscii() {
  byte index = 0;
  byte timeout = 0;
  byte ch=0;
  char data[64] = "";

  do {
    if (Serial.available() == 0) {
      delay(10);
      timeout++;
    }
    else {
      ch= Serial.read();
      data[index] =ch;
      timeout = 0;
      index++;
    }
  }  
  while ( ch!=';' && timeout<5 && index<64);
  return atof(data);
}  

void writeFloat(float val)
{
  char *addr=(char *)(&val);
  Serial.write(addr[0]);
  Serial.write(addr[1]);
  Serial.write(addr[2]);
  Serial.write(addr[3]);
}

float readFloat()
{
  float val;
  char *addr=(char *)&val;
  addr[0]=Serial.read();
  addr[1]=Serial.read();
  addr[2]=Serial.read();
  addr[3]=Serial.read();
  
  return val;
}

void writeInt(int val)
{
  Serial.write(val&0xff);
  Serial.write(val>>8);
  
}

int readInt(void)
{
  int val;
  
  val=Serial.read()<<8;
  val|=Serial.read();
}

void writeFP(float val) // fixed point send serial
{
   writeInt(val*10);
}

float readFP(void)
{
  return readInt()/10.0;
}


